package com.cyanite.playlv2.widget;

import com.cyanite.playlv2.util.CheckinTimestampSort;
import com.cyanite.playlv2.util.RemoteResourceManager;
import com.cyanite.playlv2api.types.Trip;
import com.cyanite.playlv2api.util.ConstantsUtils.TripProcessConsts;
import com.cyanite.playlv2api.util.ConstantsUtils.TripTypeConsts;
import com.cyanite.playlv2.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.IOException;
import java.util.Observable;
import java.util.Observer;

public class HotSubTripListAdapter extends BaseTripAdapter implements ObservableAdapter {

    private LayoutInflater mInflater;
    private RemoteResourceManager mRrm;
    private RemoteResourceManagerObserver mResourcesObserver;
    private ButtonRowClickHandler mClickListener;
    private boolean mMoreRefresh;
    private Handler mHandler = new Handler();
    private Context mContext;

    public HotSubTripListAdapter(Context context, RemoteResourceManager rrm,ButtonRowClickHandler clickListener) {
        super(context);
        mInflater = LayoutInflater.from(context);
        mRrm = rrm;
        mResourcesObserver = new RemoteResourceManagerObserver();
        mRrm.addObserver(mResourcesObserver);
        mClickListener = clickListener;
        mMoreRefresh = false;
        mContext = context;
    }

    public void removeObserver() {
        mHandler.removeCallbacks(mUpdatePhotos);
        mRrm.deleteObserver(mResourcesObserver);
    }

    public void setMoreRefresh(boolean isRefresh)    {
        mMoreRefresh = isRefresh;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.trip_list_hot_showing, null);
            holder = new ViewHolder();
            holder.photo = (ImageView) convertView.findViewById(R.id.imgTripPhoto);
            holder.name = (TextView) convertView.findViewById(R.id.tvTripName);
            holder.username = (TextView) convertView.findViewById(R.id.tvUserName);
            holder.type = (TextView) convertView.findViewById(R.id.tvTripType);
            holder.textLine1 = (TextView) convertView.findViewById(R.id.tvTripDescription1);
            holder.textLine2 = (TextView) convertView.findViewById(R.id.tvTripDescription2);
            holder.focused = (TextView) convertView.findViewById(R.id.tvFocused);
            holder.more = (LinearLayout) convertView.findViewById(R.id.llMore);
            holder.mProgressBarMore = (ProgressBar) convertView.findViewById(R.id.pbMore);
            holder.more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    holder.mProgressBarMore.setVisibility(View.VISIBLE);
                    mMoreRefresh = true;
                    mClickListener.onMoreClick();
                }
            });
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        convertView.setPadding(0, 3, 7, 10);

        if  ( position != getCount()-1 )    {
            holder.more.setVisibility(View.GONE);
            holder.photo.setVisibility(View.VISIBLE);
            holder.name.setVisibility(View.VISIBLE);
            holder.type.setVisibility(View.VISIBLE);
            holder.textLine1.setVisibility(View.VISIBLE);
            holder.textLine2.setVisibility(View.VISIBLE);

            Trip trip = (Trip) getItem(position);
            if (trip.getPhoto() != null && !trip.getPhoto().equals("")) {
                Uri photoUri = Uri.parse(trip.getPhoto());
                if (!mRrm.exists(photoUri)) {
                    mRrm.request(photoUri);
                }
            }
            if (trip.getCategoryId() > -1 && trip.getCategoryId() < 7) {
                holder.type.setText(TripTypeConsts.tripTypeRes[trip.getCategoryId()]);
            }
            holder.name.setText(trip.getName());
            holder.username.setText(trip.getUserName());
            holder.textLine1.setText(trip.getStartpoint() + "-" + trip.getEndpoint());
            holder.focused.setText(String.format(mContext.getString(R.string.trip_hot_focused),trip.getFocusedCount()));
            if (trip.getPhoto() != null && !trip.getPhoto().equals("")) {
                final Uri photoUri = Uri.parse(trip.getPhoto());
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri));
                    trip.setPhotoBitmap(bitmap);
                    holder.photo.setImageBitmap(bitmap);
                } catch (IOException e) {
                    holder.photo.setImageResource(R.drawable.trip_default_photo);
                }
            }   else {
                holder.photo.setImageResource(R.drawable.trip_default_photo);
            }
            holder.photo.setOnClickListener(mOnClickListenerTripImage);
            holder.photo.setTag(position);
            String timeInterval = "";
            if (trip.getUpdateTime() > 0)   {
                CheckinTimestampSort timestamps = new CheckinTimestampSort();
                try {
                    float hours = (float)(timestamps.getBoundaryAccurateRecent().getTime() - trip.getUpdateTime()*1000)/3600000;
                    if (hours < 1 && hours > 0) {
                        timeInterval = String.format(convertView.getResources().getString(R.string.trip_activity_update_time_interval_min_format), (int)(hours*60));
                    } else if (hours <= 24 && hours >= 1) {
                        timeInterval = String.format(convertView.getResources().getString(R.string.trip_activity_update_time_interval_hour_format), (int)hours);
                    } else if (hours > 24 && hours/24 <= 3) {
                        timeInterval = String.format(convertView.getResources().getString(R.string.trip_activity_update_time_interval_day_format), (int)(hours/24));
                    } else {
                        timeInterval = convertView.getResources().getString(R.string.trip_activity_update_time_interval);
                    }
                } catch (Exception ex) {
                    timeInterval = convertView.getResources().getString(R.string.trip_activity_update_time_interval);
                }
            }   else    {
                timeInterval = convertView.getResources().getString(R.string.trip_activity_update_time_interval);
            }

            String info = convertView.getResources().getString(TripProcessConsts.getTripProcessRes(trip.getProcess()));
            info += "    " + timeInterval;
            holder.textLine2.setText(info);

        } else {
            holder.more.setVisibility(View.VISIBLE);
            holder.photo.setVisibility(View.GONE);
            holder.name.setVisibility(View.GONE);
            holder.type.setVisibility(View.GONE);
            holder.textLine1.setVisibility(View.GONE);
            holder.textLine2.setVisibility(View.GONE);
        }
        if (!mMoreRefresh)  {
            holder.mProgressBarMore.setVisibility(View.GONE);
        }

        return convertView;
    }

    private class RemoteResourceManagerObserver implements Observer {
        @Override
        public void update(Observable observable, Object data) {
            mHandler.post(mUpdatePhotos);
        }
    }

    private OnClickListener mOnClickListenerTripImage = new OnClickListener() {
        @Override
        public void onClick(View v) {
            mClickListener.onImageClick((Trip)getItem((Integer) v.getTag()));
        }
    };

    public interface ButtonRowClickHandler {
        public void onImageClick(Trip trip);
        public void onMoreClick();
    }

    private Runnable mUpdatePhotos = new Runnable() {
        @Override
        public void run() {
            notifyDataSetChanged();
        }
    };

    private static class ViewHolder {
        ImageView photo;
        TextView name;
        TextView username;
        TextView textLine1;
        TextView textLine2;
        TextView type;
        TextView focused;
        LinearLayout more;
        ProgressBar mProgressBarMore;
    }
}
